use generator_prompts::chat::prompts_default_template;
use model_graph_types::{
    assistant::{
        prompts::PromptTemplate,
        ability::AssistantAbility,
        chat::{ChatMessage, ChatOptions},
    },
    connector::{Connector, QueryOptions},
    modeling::Value,
};
use std::collections::HashMap;

use crate::get_system_connector;

pub async fn prompts_query_templates(
    ability: AssistantAbility,
    selector: HashMap<String, String>,
) -> anyhow::Result<Vec<PromptTemplate>> {
    //获取connector
    let connector = get_system_connector().await?;

    let args: Vec<Value> = vec![Value::String(ability.clone().try_into()?)];

    let (_, rows) = connector
        .query(
            &String::from(
                "select system, prompt, options, selector from assistant_prompts where ability = $1",
            ),
            &args,
            QueryOptions {},
        )
        .await?;

    let mut templates: Vec<PromptTemplate> = vec![];

    for row in rows {
        //每一个表
        match row {
            Value::Array(cols) => {
                let system = cols.get(0).map_or(String::new(), |f| match f {
                    Value::String(v) => v.clone(),
                    _ => String::new(),
                });

                let prompt = cols.get(1).map_or(String::new(), |f| match f {
                    Value::String(v) => v.clone(),
                    _ => String::new(),
                });

                let options = cols.get(2).map_or(String::new(), |f| match f {
                    Value::String(v) => v.clone(),
                    _ => String::new(),
                });

                let selector = cols.get(3).map_or(String::new(), |f| match f {
                    Value::String(v) => v.clone(),
                    _ => String::new(),
                });

                templates.push(PromptTemplate::new(&system, &prompt, &options)?);
            }
            _ => {
                tracing::debug!("==");
            }
        }
    }
    //默认的
    if templates.len() == 0 {
        let defaults = prompts_default_template(ability.clone(), selector).await?;
        Ok(defaults)
    } else {
        Ok(templates)
    }
}

pub async fn prompts_query_one_template(
    ability: AssistantAbility,
    selector: HashMap<String, String>,
) -> anyhow::Result<PromptTemplate> {
    //

    prompts_query_templates(ability, selector)
        .await?
        .pop()
        .map_or(Err(anyhow::anyhow!("")), |v| Ok(v))
}
